/**
 * Description:
 * Class Name:QueryExecutor
 * Date:2022/4/10 12:20
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第13章_MySQL数据库和JDBC编程._13_5_管理结果集._13_5_3_使用ResultSetMetaData分析结果集;

import java.io.FileReader;
import java.sql.*;
import java.util.Properties;

public class QueryExecutor {
    private String driver;
    private String url;
    private String user;
    private String pwd;

    public void initParam(String paramFilePath) throws Exception{
        Properties props = new Properties();
        props.load(new FileReader(paramFilePath));
        driver = props.getProperty("driver");
        url = props.getProperty("url");
        user = props.getProperty("user");
        pwd = props.getProperty("pwd");
    }

    public void doExecute(String sql) throws Exception{
        try(
                Connection connection = DriverManager.getConnection(url, user, pwd);
                Statement statement = connection.createStatement();
                ResultSet resultSet = statement.executeQuery(sql);
                ){
            // 通过ResultSet对象的getMetaData()方法来获取它的ResultSetMetaData对象
            ResultSetMetaData rsmd = resultSet.getMetaData();
            // 打印ResultSet的描述信息
            int col_num = rsmd.getColumnCount();
            System.out.println("select出结果集的列数为：" + col_num);
            for (int i = 1; i <= col_num; i++) {
                System.out.println(i + "索引列的列名是：" + rsmd.getColumnName(i) + "，列的数据类型是：" + rsmd.getColumnTypeName(i));
            }
        }
    }

    public static void main(String[] args) throws Exception{
        var qe = new QueryExecutor();
        qe.initParam("Chapter_13_mysql.ini");
        Class.forName(qe.driver);

        String sql = "select * from student_table";
        qe.doExecute(sql);
    }
}
